import re
import requests
import json
import pymysql
from OpManager import settings
import time

sqlconn = pymysql.connect(settings.mysql['ip'], settings.mysql['user'], settings.mysql['passwd'],
                          settings.mysql['database'])
cursor = sqlconn.cursor()
sql = "select * from setting WHERE id=1"
cursor.execute(sql)
getres = cursor.fetchone()
sqlconn.close()
zabbix_url = getres[2]
if getres:
    apiurl = zabbix_url + "/api_jsonrpc.php"
else:
    print("请在数据库id为1的数据中设置好zabbix链接")


def readtoken():
    try:
        TokkenFile = open('/tmp/zabbix_tokken', 'r')
    except FileNotFoundError:
        gettoken()
        TokkenFile = open('/tmp/zabbix_tokken', 'r')
    tokken = TokkenFile.read()
    return tokken


def postAPI(datas):
    tokken = readtoken()
    postDatas = datas
    header = {"Content-Type": "application/json"}
    postDatas['auth'] = tokken
    postDatas['id'] = 1
    postDatas = json.dumps(postDatas)
    testurl = re.findall("http", apiurl)
    if testurl:
        try:
            res = requests.post(url=apiurl, data=postDatas, headers=header)
            res = json.loads(res.text)
        except Exception as e:
            print("获取失败，请检查本系统关于Zabbix的配置是否正确", e)
            res = {"result": ""}
        if 'error' in res:
            print('tokken错误，重新获取tokken')
            gettoken()
            res = postAPI(datas)
            time.sleep(1)
    else:
        print("跳过获取，用户未设置含有http的url")
        res = {"result": ""}
    return res['result']


def gettoken():
    header = {"Content-Type": "application/json"}
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "user": "Op",
            "password": "Op"
        },
        "id": 1
    })
    try:
        res = requests.post(url=apiurl, data=data, headers=header)
        res = json.loads(res.text)
        print("向 " + apiurl + " 请求结果为：")
        print(res)
    except requests.exceptions.ConnectionError as e:
        print("Zabbix网址错误:\"" + str(e) + "\"")
        res = {"result": "Zabbix网址错误"}
    except requests.exceptions.MissingSchema as e:
        print("Zabbix网址未配置:\"" + str(e) + "\"")
        res = {"result": "Zabbix网址未配置"}
    try:
        tokken = res["result"]
        TokkenFile = open('/tmp/zabbix_tokken', 'w')
        TokkenFile.write(tokken)
        TokkenFile.close()
    except KeyError:
        # echo_log
        return res["error"]
    except Exception as e:
        error_msg = "发生了未知的错误"
        print(e)
        # echo_log
        return error_msg


def getProblems():
    data = {
        "jsonrpc": "2.0",
        "method": "problem.get",
        "params": {
            "tags": []
        }
    }
    return postAPI(data)


def getHosts():
    data = {
        "jsonrpc": "2.0",
        "method": "hostinterface.get",
        "params": {
            "output": "extend"
        }
    }
    return postAPI(data)


if __name__ == '__main__':
    gettoken()
    # getProblems()
    # print(getHosts())
